package com.otv.core;

import java.util.List;

import javax.naming.InitialContext;
import javax.naming.NamingException;
import javax.persistence.EntityManager;
import javax.persistence.Query;

import com.otv.model.Magasin;

public class CoreHelper {

	@SuppressWarnings("rawtypes")
	public static List getResultByAttribute(EntityManager entityManager,
			Class clazz, String attribute, String attributeValue) {

		System.out.println("hi");

		String className = clazz.getSimpleName();
		String query = "from " + className + " x where x." + attribute + "='"
				+ attributeValue + "'";
		Query createNamedQuery = entityManager.createQuery(query);

		List resultList2 = createNamedQuery.getResultList();

		return resultList2;

	}

	@SuppressWarnings("rawtypes")
	public static List getResultByAttribute(EntityManager entityManager,
			Class clazz, String attribute, String attributeValue,
			boolean addQuote) {

		System.out.println("hi");

		String className = clazz.getSimpleName();
		String query;
		if (addQuote) {
			query = "from " + className + " x where x." + attribute + "='"
					+ attributeValue + "'";
		} else {
			query = "from " + className + " x where x." + attribute + "="
					+ attributeValue;
		}
		Query createNamedQuery = entityManager.createQuery(query);

		List resultList2 = createNamedQuery.getResultList();

		return resultList2;

	}

	public static Object getJndiContext(Class clazz) {
		String simpleName = clazz.getSimpleName();
		String lookup = "java:module/" + simpleName + "!" + clazz.getName();
		Object ret;
		try {
			InitialContext localInitialContext = new InitialContext();
			ret = localInitialContext.lookup(lookup);
		} catch (NamingException localNamingException) {
			System.out.println("error");
			return null;
		}
		return ret;
	}

	@SuppressWarnings({ "unchecked", "rawtypes" })
	public static <T> List<T> getAllValues(EntityManager entityManager,
			Class<T> clazz) {
		String className = clazz.getSimpleName();
		String query;

		query = "from " + className;

		Query createNamedQuery = entityManager.createQuery(query);

		List resultList2 = createNamedQuery.getResultList();

		return resultList2;
	}

}
